#!/usr/bin/env bash

NSname=$1
ipcname="$1"

#when start bootnode, leave this empty
bootnode_addr=$2

helper_path="/tmp/meth/helper"
home_path="/tmp/meth/linux/home/${NSname}"

if [[ "" == $bootnode_addr ]]; then
    worker="/tmp/meth/parity${NSname}"
    mark=3
elif [[ 1 -eq $[$RANDOM % 5] ]]; then
    worker="/tmp/meth/geth${NSname}"
    mark=1
else
    worker="/tmp/meth/parity${NSname}"
    mark=2
fi

# use parity as bootnode
start_parity() {
    CMDX="$worker --chain ${helper_path}/parity-genesis.json \
        --base-path=${home_path} \
        --no-ws --no-jsonrpc --ipc-apis=all --ipc-path=${home_path}/eth.ipc"

    if [[ 3 -ne mark ]]; then
        CMDX=${CMDX}" --bootnodes=$bootnode_addr"
    fi

    ip netns exec ${NSname} bash -c "$CMDX;wait" || exit 1
}

start_geth() {
    CMD="$worker --datadir ${home_path} init ${helper_path}/geth-genesis.json \
        && $worker --datadir ${home_path} --v5disc \
                    --ipcpath ${home_path}/eth.ipc \
                    --bootnodes ${bootnode_addr}"

    # miner appear 1/2/5 = 1/10 = 10%
    if [[ 1 -eq $[$RANDOM % 2] ]]; then
        CMD=$CMD" --mine --miner.threads 1 --etherbase 0x7777777777777777777777777777777777777777"
    fi

    ip netns exec ${NSname} bash -c "$CMD;wait" || exit 1
}

if [[ 1 -eq $mark ]]; then
    start_geth &
else
    start_parity &
fi

